package com.flyoil.petromp.utils.Dialog;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.cnpc.fyupdate.download.DownInfo;
import com.cnpc.fyupdate.download.DownState;
import com.cnpc.fyupdate.download.HttpDownManager;
import com.cnpc.fyupdate.listener.HttpDownOnNextListener;
import com.cnpc.fyupdate.utils.AppUtil;
import com.cnpc.fyupdate.utils.DbDownUtil;
import com.cnpc.fyupdate.utils.UpdataConstant;
import com.cnpc.fyutils.ToastUtils;
import com.flyoil.petromp.R;
import com.flyoil.petromp.base.MyApplication;
import com.flyoil.petromp.utils.MoccaPreferences;
import com.flyoil.petromp.view.TextProgressBar;

import java.io.File;
import java.util.List;

import rx.Observable;
import rx.Observer;

/**
 * @author bingju
 *
 */
public class UpdataDialog extends Dialog {

	private View iv_cancel;
	private TextView tv_confirm;
	private TextView tv_content;
	private TextView tv_version_code;
	private TextView tv_storage;
	private TextProgressBar progress_bar_ada;
	private ImageView iv_isconfirm;
	private ImageView iv_delete;

	private String content;
	private String version;
	private String storage;
	private OnClickListener positiveClickListener;
	private OnClickListener negativeClickListener;
	private OnClickListener selfClickListener;

	private String imageUrl;

	private DbDownUtil dbUtil;
	private HttpDownManager manager;
	private List<DownInfo> listData;
	private DownInfo downInfo;
	private boolean isDownLoad = false;

	public interface OnClickListener {
		void onClick();
	}
	private String checkNull(String s) {
		if (s == null || s.trim().length() < 1) {
			return "";
		}
		return s.trim();
	}
	public UpdataDialog(Context context, int layout_id, boolean cancelable, OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
	}

	public UpdataDialog(Context context, int theme) {
		super(context, theme);
	}

	public UpdataDialog setDialogContent(String content) {
		this.content = checkNull(content);
		return this;
	}
	public UpdataDialog setVersionCode(String version) {
		this.version = checkNull(version);
		return this;
	}
	public UpdataDialog setImageUrl(String imageUrl) {
		this.imageUrl = checkNull(imageUrl);
		return this;
	}
	public UpdataDialog setStorage(String storage) {
		this.storage = checkNull(storage);
		return this;
	}
	public UpdataDialog setPostitveButton(String positive, OnClickListener onclickListener) {
		this.positiveClickListener = onclickListener;
		return this;
	}

	public UpdataDialog setNegativeButton(OnClickListener onclickListener) {
		this.negativeClickListener = onclickListener;
		return this;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_check_update);
		this.setCancelable(false);

		iv_cancel = findViewById(R.id.iv_cancel);
		iv_isconfirm = (ImageView) findViewById(R.id.iv_isconfirm);
		iv_delete = (ImageView) findViewById(R.id.iv_delete);
		tv_confirm = (TextView) findViewById(R.id.tv_confirm);
		tv_content = (TextView) findViewById(R.id.tv_content);
		tv_version_code = (TextView) findViewById(R.id.tv_version_code);
		tv_storage = (TextView) findViewById(R.id.tv_storage);
		progress_bar_ada = (TextProgressBar) findViewById(R.id.progress_bar_ada);
//		progress_bar_ada.setProgress(100);

		if (!TextUtils.isEmpty(content))
			tv_content.setText(content);
		if (!TextUtils.isEmpty(version))
			tv_version_code.setText(version);
		if (!TextUtils.isEmpty(storage))
			tv_storage.setText(storage);
//
		iv_cancel.setOnClickListener(mOnClickListener);
		tv_confirm.setOnClickListener(mOnClickListener);
		iv_isconfirm.setOnClickListener(mOnClickListener);
		iv_delete.setOnClickListener(mOnClickListener);
//		tv_confirm.setVisibility(View.GONE);
//		progress_bar_ada.setOnClickListener(mOnClickListener);
		initResource();
	}
	private void initResource() {
		dbUtil= DbDownUtil.getInstance();
		manager= HttpDownManager.getInstance();
		dbUtil.deleteDownAll();
		listData=dbUtil.queryDownAll();
        /*第一次模拟服务器返回数据掺入到数据库中*/
		if(listData.isEmpty()){
//			String[] downUrl=new String[]{"http://www.izaodao.com/app/izaodao_app.apk"};
			String[] downUrl=new String[1];
			downUrl[0] = checkNull(imageUrl).length() < 1 ? "http://repair.flyoil.cn/apk/repairandroidbx.apk" : imageUrl;
			for (int i = 0; i < downUrl.length; i++) {
//                File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
//                        "test"+i + ".apk");
				File outputFile = new File(AppUtil.initAPKDir(getContext()),"test"+i+".apk");
				DownInfo apkApi=new DownInfo(downUrl[i]);
				apkApi.setId(i);
				apkApi.setState(DownState.START);
				apkApi.setSavePath(outputFile.getAbsolutePath());
				dbUtil.save(apkApi);
			}
			listData=dbUtil.queryDownAll();
		}

	}
	private void loadData(List<DownInfo> listData) {
		Observable.from(listData)
				.first()
				.subscribe(new Observer<DownInfo>() {
					@Override
					public void onCompleted() {

					}

					@Override
					public void onError(Throwable e) {

					}

					@Override
					public void onNext(DownInfo downInfo) {
						downInfo.setListener(httpProgressOnNextListener);
						manager.startDown(downInfo);
					}
				});
	}
	/*下载回调*/
	HttpDownOnNextListener<DownInfo> httpProgressOnNextListener=new HttpDownOnNextListener<DownInfo>() {
		@Override
		public void onNext(DownInfo baseDownEntity) {
//			tv_confirm.setText("更新完成");
			progress_bar_ada.setStateType(UpdataConstant.FINISH);
			openFile(new File(baseDownEntity.getSavePath()));
			dismiss();

		}

		@Override
		public void onStart() {
			progress_bar_ada.setStateType(UpdataConstant.DOWNLOAD);
//			tv_confirm.setBackgroundColor(Color.parseColor("#00000000"));
//			tv_confirm.setText("开始更新");
		}

		@Override
		public void onComplete() {
//			tv_confirm.setText("更新完成");
			progress_bar_ada.setStateType(UpdataConstant.FINISH);
			dismiss();
		}

		@Override
		public void onError(Throwable e) {
			super.onError(e);
			ToastUtils.show_toast("网络异常，请稍后重试!");
			startOrPause();
		}


		@Override
		public void onPuase() {
			super.onPuase();
//			tv_confirm.setText("暂停");
			progress_bar_ada.setStateType(UpdataConstant.PAUSE);
		}

		@Override
		public void onStop() {
			super.onStop();
		}

		@Override
		public void updateProgress(long readLength, long countLength) {
			progress_bar_ada.setStateType(UpdataConstant.DOWNLOAD);
			progress_bar_ada.setProgress(countLength <= 0 ? 0f : (float) ((readLength * 100) / countLength));

		}
	};
	private void openFile(File file) {
		MoccaPreferences.app_new_versions.put(false);

		// TODO Auto-generated method stub
		//Intent intent = new Intent();
//		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		intent.setAction(Intent.ACTION_VIEW);
//		if (Build.VERSION.SDK_INT >= 24) {
//			// 由于没有在Activity环境下启动Activity,设置下面的标签
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
//			Uri apkUri = FileProvider.getUriForFile(getContext(), "com.bjfontcl.repairandroidbx.fileprovider", file);
//			//添加这一句表示对目标应用临时授权该Uri所代表的文件
//			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//			intent.setDataAndType(apkUri, "applicationnd.android.package-archive");
//		} else {
//			intent.setDataAndType(Uri.fromFile(file),
//					"applicationnd.android.package-archive");
//		}
//
////		intent.setDataAndType(Uri.fromFile(file),
////				"application/vnd.android.package-archive");
//		getContext().startActivity(intent);
		//		System.exit(0);//正常退出App


		Uri uri = null;
		if (Build.VERSION.SDK_INT >= 24) {
			uri = FileProvider.getUriForFile(getContext(), "com.flyoil.petromp.fileprovider",file);
		} else {
			uri = Uri.fromFile(file);
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		getContext().startActivity(intent);
	}

	@Override
	public void dismiss() {
		super.dismiss();
		/*记录退出时下载任务的状态-复原用*/
		for (DownInfo downInfo : listData) {
			manager.pause(downInfo);
			dbUtil.update(downInfo);
		}
		MyApplication.exitActivity();//关闭APP
	}

	private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tv_confirm:
				if (positiveClickListener != null)
					positiveClickListener.onClick();
				alphaAnimRun(tv_confirm);
//				dismiss();

//
				break;
//			case R.id.progress_bar_ada:
//
//					break;
			case R.id.iv_cancel://取消弹框不进行版本更新
				if (negativeClickListener != null)
					negativeClickListener.onClick();
				MoccaPreferences.app_new_versions.put(true);
				dismiss();
				break;
			case R.id.iv_isconfirm:
				startOrPause();
				break;
			case R.id.iv_delete:
				MoccaPreferences.app_new_versions.put(true);
				dismiss();
				break;
			default:
				break;
			}
		}
	};
	private void startOrPause() {
		if (isDownLoad) {
			isDownLoad = false;
			iv_isconfirm.setSelected(false);
			manager.pause(listData.get(0));
		} else {
			isDownLoad = true;
			iv_isconfirm.setSelected(true);
//					manager.startDown(listData.get(0));
			loadData(listData);
		}
	}

	public void alphaAnimRun(final View view)
	{
		ObjectAnimator anim = ObjectAnimator//
				.ofFloat(view, "alpha", 1.0F,  0.0F)//
				.setDuration(500);//
		anim.start();
		anim.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				tv_confirm.setVisibility(View.GONE);
				startOrPause();
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});
	}
}
